package com.suxin.builder;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @author Tang
 * @classname BeanBuilder
 * @description [ 通用的bean构建 ]
 * @date 2022/11/30 16:38
 */
public class BeanBuilder<T> {

    private final List<Consumer<T>> setPropertyList = new ArrayList<>(8);

    private final T instance;

    private BeanBuilder(Supplier<T> constructorSupplier) {
        this.instance = constructorSupplier.get();
    }

    public static <R> BeanBuilder<R> withConstructor(Supplier<R> constructorSupplier) {
        return new BeanBuilder<>(constructorSupplier);
    }

    public <R> BeanBuilder<T> withConsumer(ConsumerAccept<T, R> biConsumer, R value) {
        Consumer<T> consumer = beanInstance -> biConsumer.accept(beanInstance, value);
        setPropertyList.add(consumer);
        return this;
    }

    public T build() {
        for (Consumer<T> tConsumer : setPropertyList) {
            tConsumer.accept(instance);
        }
        return instance;
    }

    @FunctionalInterface
    public interface ConsumerAccept<T, R> {
        /**
         * accept
         * @param t t
         * @param u u
         */
        void accept(T t, R u);
    }

    public static void main(String[] args) {
        User user = new BeanBuilder<User>(User::new)
                .withConsumer(User::setName, "hello")
                .withConsumer(User::setAge, 18)
                .build();
        System.out.println(user);
    }

    @Data
    public static class User{
        private Integer age;
        public String name;
    }

}